/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import main.Constants;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.UtopiaTime;
import database.DBConnectionFactory;

/**
 * Represents an Event
 * 
 * 
 */
public class Event implements BotObject, Comparable<Event> {
   /**
    * Removes the specified event
    * 
    * @param args
    *           The description of the event to be removed
    * @return true if the event is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("DELETE FROM event WHERE description = ?");
		 ps.setString(1, args[0]);
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of regular events (i.e. wave not included)
    * 
    * @returna List of Event objects
    */
   public static List<Event> getEvents() {
	  List<Event> out = new LinkedList<Event>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM event WHERE eventtype = false ORDER BY eventtime DESC");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new Event(rs.getString("description"), rs.getTimestamp("eventtime").getTime(), false, rs.getTimestamp(
				  "settime").getTime()));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns the wave
    * 
    * @return an Event object. Returns null if no wave is found
    */
   public static Event getWave() {
	  Event out = null;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM event WHERE eventtype = true");
		 rs = ps.executeQuery();

		 if (rs.next()) {
			out = new Event("", rs.getTimestamp("eventtime").getTime(), true, rs.getTimestamp("settime").getTime());
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private String description = "";

   private Long eventtime = 0L;

   private boolean eventtype = false;

   private Long settime = 0L;

   public Event(final String description, final Long eventtime, final boolean eventtype, final Long settime) {
	  this.description = description;
	  this.eventtime = eventtime;
	  this.eventtype = eventtype;
	  this.settime = settime;
   }

   /**
    * Compares two events based on what time they were added
    */
   @Override
   public int compareTo(final Event o) {
	  if (eventtime < o.getEventtime())
		 return -1;
	  else if (equals(o))
		 return 0;
	  else
		 return 1;
   }

   /**
    * Considers two events equal if they were added at the same time, seeing as the purpose is merely to order them by age
    */
   @Override
   public boolean equals(final Object o) {
	  if (o == null)
		 return false;
	  if (o instanceof Event)
		 return settime.equals(((Event) o).getSettime());
	  return false;
   }

   public String getDescription() {
	  return description;
   }

   public Long getEventtime() {
	  return eventtime;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (getDescription() == null || getEventtime() == null || getSettime() == null)
		 return out;
	  if (outputType == Constants.EVENT && args.length == 2) {
		 String pattern = "EEE, MMM d, H:mm:ss";
		 SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
		 sdf.setTimeZone(TimeZone.getTimeZone("GMT" + args[0]));
		 final UtopiaTime ut = new UtopiaTime(getEventtime());
		 out.add(Colors.BLUE + "Event #" + args[1] + ": " + Colors.OLIVE + getDescription() + Colors.RED + ". Utodate: "
			   + Colors.BLUE + ut.formattedUT());
		 out.add(Colors.RED + "RL time: " + Colors.BLUE + sdf.format(new java.util.Date(getEventtime())));
	  } else if (outputType == Constants.WAVE_REAL_TIME) {
		 String pattern = "EEE, MMM d, H:mm:ss";
		 SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
		 sdf.setTimeZone(TimeZone.getTimeZone("GMT" + args[0]));
		 String out1 = sdf.format(new java.util.Date(getEventtime()));

		 out.add("Wave is " + out1 + " your time");
	  } else if (outputType == Constants.WAVE_UTO_TIME) {
		 final UtopiaTime ut = new UtopiaTime(getEventtime());
		 out.add(Colors.OLIVE + "Wave time: " + Colors.BLUE + ut.formattedUT() + Colors.OLIVE + ". Time left: " + Colors.BLUE
			   + UtopiaTime.compareTimes(ut.getTime()));
	  }
	  return out;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (getDescription() == null || getEventtime() == null || getSettime() == null)
		 return out;
	  out.put("Description", getDescription());
	  out.put("Event Time", new Date(getEventtime()));
	  out.put("Event Type", isWave() ? "Wave" : "Event");
	  out.put("Set Time", new Date(getSettime()));
	  return out;
   }

   public Long getSettime() {
	  return settime;
   }

   @Override
   public int hashCode() {
	  assert false : "hashCode not designed";
	  return 42; // any arbitrary constant will do
   }

   public boolean isWave() {
	  return eventtype;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (getDescription() == null || getEventtime() == null || getSettime() == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 deleteFromDB(getDescription());

		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("INSERT INTO event VALUES(?,?,?,?)");
		 ps.setBoolean(1, isWave());
		 ps.setString(2, getDescription());
		 ps.setTimestamp(3, new Timestamp(getEventtime()));
		 ps.setTimestamp(4, new Timestamp(getSettime()));
		 ps.executeUpdate();
		 out = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   public void setIsWar(final boolean eventtype) {
	  this.eventtype = eventtype;
   }
}
